﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.Public.Output;
using MesProjectWinform.WareHouse.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.仓库定义
{
    // 定义委托，用于传递员工字典数据
    public delegate void EmpDataTransferHandler(Dictionary<string, string> empData);

    public partial class Form_CheckEmp : DevExpress.XtraEditors.XtraForm
    {
        // 声明事件，用于数据传递
        public event EmpDataTransferHandler OnEmpDataSelected;

        // 分页参数
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;

        // 用于存储预选员工ID
        //private Dictionary<string, string> preSelectedEmpIds = new Dictionary<string, string>();

        public Form_CheckEmp()
        {
            InitializeComponent();

            // 初始化分页控件
            InitPaginationControl();
        }

        /// <summary>
        /// 设置预选员工
        /// </summary>
        /// <param name="empIds">员工ID字典</param>
        public void SetPreSelectedEmployees(Dictionary<string, string> empIds)
        {
            if (empIds != null && empIds.Count > 0)
            {
                // preSelectedEmpIds = new Dictionary<string, string>(empIds);
                listSelEmpID = new Dictionary<string, string>(empIds);
            }
        }

        private Dictionary<string, string> listSelEmpID = new Dictionary<string, string>();
        int Index;

        // 添加公共属性返回选中的员工ID字典
        public Dictionary<string, string> SelectedEmployees
        {
            get { return listSelEmpID; }
        }

        // 添加对话框结果标识
        public bool IsConfirmed { get; private set; } = false;

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPaginationControl()
        {
            try
            {
                // 先移除已有的事件处理程序，避免重复绑定
                paginationControl1.PageChanged -= PaginationControl_PageChanged;
                paginationControl1.PageSizeChanged -= PaginationControl_PageSizeChanged;

                // 设置分页控件属性
                paginationControl1.PageSizeOptions = new List<int> { 5, 10, 20, 50, 100 };
                paginationControl1.PageSize = pageSize;
                paginationControl1.CurrentPage = currentPage;
                paginationControl1.TotalRecords = totalRecords;

                // 绑定分页事件
                paginationControl1.PageChanged += PaginationControl_PageChanged;
                paginationControl1.PageSizeChanged += PaginationControl_PageSizeChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化分页控件时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                // 调用API获取分页数据
                string action = WareHouseGolab.GetEMPCode + $"?pageNum={currentPage}&pageSize={pageSize}&DepId=D25070400005";
                SelItemsIdEmpAsync(action);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载分页数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 人员填充
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public void SelItemsIdEmpAsync(string action = WareHouseGolab.GetEMPCode)
        {
            try
            {
                HttpClientHelper helper = new HttpClientHelper();
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                // 解析JSON响应
                ApiPaging<List<UserLoginOutput>> model = JsonConvert.DeserializeObject<ApiPaging<List<UserLoginOutput>>>(json);

                if (model == null || model.Data == null)
                {
                    MessageBox.Show("获取数据失败，返回结果为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 确保在UI线程上更新控件
                if (EmpGridView.InvokeRequired)
                {
                    EmpGridView.Invoke(new Action(() => UpdateUIWithData(model)));
                }
                else
                {
                    UpdateUIWithData(model);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取人员数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 使用获取的数据更新UI
        /// </summary>
        private void UpdateUIWithData(ApiPaging<List<UserLoginOutput>> model)
        {
            try
            {
                // 将数据转换为DataTable
                DataTable dt = DataConverHelper.ToDataTable(model.Data);

                // 更新数据网格
                EmpGridView.DataSource = dt;

                // 更新分页控件
                if (paginationControl1 != null)
                {
                    totalRecords = model.TotalCount;
                    paginationControl1.TotalRecords = totalRecords;
                    paginationControl1.CurrentPage = currentPage;
                    paginationControl1.PageSize = pageSize;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新UI数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 页码改变事件
        /// </summary>
        private void PaginationControl_PageChanged(object sender, PageChangedEventArgs e)
        {
            try
            {
                currentPage = e.CurrentPage;
                pageSize = e.PageSize;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("页码改变处理时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 每页记录数改变事件
        /// </summary>
        private void PaginationControl_PageSizeChanged(object sender, PageSizeChangedEventArgs e)
        {
            try
            {
                currentPage = e.CurrentPage;
                pageSize = e.PageSize;

                // 使用BeginInvoke确保UI线程完成当前操作后再加载数据
                BeginInvoke(new Action(() =>
                {
                    try
                    {
                        LoadData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("加载数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show("每页记录数改变处理时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CheckEmpForm_Load(object sender, EventArgs e)
        {
            // 加载初始数据
            LoadData();

            // 加载完数据后，设置预选中的行
            if (listSelEmpID.Count > 0)
            {
                // 更新标签显示已选择的数量
                labelControl1.Text = $"已选择 {listSelEmpID.Count} 个项目。";

                // 在数据加载完成后调用方法来选中行
                Application.Idle += new EventHandler(SelectRowsAfterLoad);
            }
        }

        /// <summary>
        /// 数据加载完成后选中行
        /// </summary>
        private void SelectRowsAfterLoad(object sender, EventArgs e)
        {
            // 只执行一次
            Application.Idle -= SelectRowsAfterLoad;

            // 遍历所有行，选中预选的行
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                DataRow row = gridView1.GetDataRow(i);
                if (row != null && listSelEmpID.ContainsKey(row.ItemArray[0].ToString()))
                {
                    gridView1.SelectRow(i);
                }
            }
        }

        private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            int[] rownumber = this.gridView1.GetSelectedRows();//获取选中行号；
            int rowHandle = Index;

            var hitInfo = gridView1.CalcHitInfo(gridView1.GridControl.PointToClient(Control.MousePosition));

            // 判断是否点击的是列标题
            if (hitInfo.HitTest == GridHitTest.Column)
            {
                foreach (var rowHandle1 in rownumber)
                {
                    Boolean check = this.gridView1.IsRowSelected(rowHandle1);
                    DataRow row = this.gridView1.GetDataRow(rowHandle1);
                    if (check)
                    {
                        if (!listSelEmpID.ContainsKey(row.ItemArray[0].ToString()))
                        {
                            listSelEmpID.Add(row.ItemArray[0].ToString(), row.ItemArray[1].ToString());
                        }
                    }
                    else
                    {
                        if (listSelEmpID.ContainsKey(row.ItemArray[0].ToString()))
                        {
                            listSelEmpID.Remove(row.ItemArray[0].ToString());
                        }
                    }
                }
                if (rownumber.Length == 0)
                {
                    listSelEmpID.Clear();
                }
            }
            else
            {
                //DataRow row = this.gridView1.GetDataRow(rownumber[0]);//根据行号获取相应行的数据；

                Boolean check = this.gridView1.IsRowSelected(rowHandle);
                DataRow row = this.gridView1.GetDataRow(rowHandle);
                if (check)
                {
                    if (!listSelEmpID.ContainsKey(row.ItemArray[0].ToString()))
                    {
                        listSelEmpID.Add(row.ItemArray[0].ToString(), row.ItemArray[1].ToString());
                    }
                }
                else
                {
                    if (listSelEmpID.ContainsKey(row.ItemArray[0].ToString()))
                    {
                        listSelEmpID.Remove(row.ItemArray[0].ToString());
                    }
                }
            }
            labelControl1.Text = $"已选择 {listSelEmpID.Count} 个项目。";
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            Index = e.RowHandle;
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            // 标记为已确认
            IsConfirmed = true;

            // 触发事件，传递选中的员工数据
            OnEmpDataSelected?.Invoke(listSelEmpID);

            // 关闭窗体
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, EventArgs e)
        {
            // 标记为取消
            IsConfirmed = false;
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
    }
}